﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jzy.Model.DocManger;

using Jzy.DAL.DocManger;
using System.Data;

using System.IO;

using Frame.Lib.Web;
using Frame.Lib.Core.Attach;
using Frame.Lib.Core.Right;
using Frame.Lib.Enums;
using Frame.Lib.Core.Base;
using Jzy.DAL;

namespace Jzy.BLL.DocManger
{
    public class DocumentBO : CommonOperate<DocumentInfo>
    {
        private DocumentDAL doc;
        protected override BaseDAL DAL
        {
            get
            {
                return doc;
            }
        }
        private DirBO dir;
        public DocumentBO()
            : base(OTableName.Document)
        {
            doc = new DocumentDAL();
            dir = new DirBO();            
        }

        #region 获得一个文档加目录的列表
        /// <summary>
        /// 获得一个文档加目录的列表(带权限控制）
        /// </summary>
        /// <param name="dirID"></param>
        /// <param name="userID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public DataTable GetDocDirList(int dirID, int userID, ListMode type)
        {

            RecordRightBO right = new RecordRightBO(OTableName.DocDirRight);
            List<int> lstDirIDs = right.GetBindIDs(userID, RecordRightName.Browse, RightOwnerType.User);//能浏览的目录ID集合

            right.TableName = OTableName.DocRight;
            List<int> lstDocIDs = right.GetBindIDs(userID, RecordRightName.Browse, RightOwnerType.User);//能浏览的文档ID集合

            DataTable dtReturn = null;
            DataTable dtDir = null;
            DataTable dtDoc = null;

            DataColumn colDir = new DataColumn("Type", typeof(int));
            colDir.AllowDBNull = false;
            colDir.DefaultValue = 1;

            DataColumn colDoc = new DataColumn("Type", typeof(int));
            colDoc.AllowDBNull = false;
            colDoc.DefaultValue = 0;

            switch (type)
            {
                case ListMode.Dir:
                    {
                        dtDir = dir.GetDataTable(dirID);
                        FilterData(dtDir, lstDirIDs, userID);
                        dtDir.Columns.Add(colDir);
                        dtReturn = dtDir;
                        break;
                    }
                case ListMode.Doc:
                    {
                        dtDoc = doc.GetList(dirID);
                        FilterData(dtDoc, lstDocIDs, userID);
                        dtDoc.Columns.Add(colDoc);
                        dtReturn = dtDoc;
                        break;
                    }
                case ListMode.DirDoc:
                    {
                        dtDir = dir.GetDataTable(dirID);
                        FilterData(dtDir, lstDirIDs, userID);
                        dtDir.Columns.Add(colDir);

                        dtDoc = doc.GetList(dirID);
                        FilterData(dtDoc, lstDocIDs, userID);
                        dtDoc.Columns.Add(colDoc);
                        //全并两个dt
                        foreach (DataRow dr in dtDir.Rows)
                        {
                            DataRow drNew = dtDoc.NewRow();
                            drNew["ID"] = dr["ID"];
                            drNew["Name"] = dr["Name"];
                            drNew["DirID"] = dr["UpperID"];
                            drNew["CreatorID"] = dr["CreatorID"];
                            drNew["CreatorName"] = dr["CreatorName"];
                            drNew["InputTime"] = dr["InputTime"];
                            drNew["Type"] = dr["Type"];
                            drNew["UserID"] = dr["UserID"];
                            dtDoc.Rows.Add(drNew);
                        }
                        dtReturn = dtDoc;
                        break;
                    }
            }
            foreach (DataRow dr in dtReturn.Rows)
            {
                if (dr["UserID"] is DBNull)
                {
                    dr["CreatorName"] += "<b style='color:red'>[已删除]</b>";
                }
            }

            return dtReturn;
        }

        //根据权限对数据进行过滤，把没有权限的行删除
        public void FilterData(DataTable dt, List<int> lstIDs, int userID)
        {
            if (userID != Constants.ADMIN_ID)//如为管理员，则拥有所有权限
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int id = (int)dt.Rows[i]["ID"];

                    if (lstIDs.IndexOf(id) < 0)
                    {
                        dt.Rows.RemoveAt(i);
                        i--;
                    }
                }
            }
        }
        #endregion

        public bool Exist(int dirID, string strName, string strDocID)
        {
            bool flag = doc.Exist(dirID, strName, strDocID);
            return flag;
        }

        public Dictionary<int, int> GetCreatorIDs(List<int> lstSelectIDs)
        {
            Dictionary<int, int> ditCreatorIDs = doc.GetCreatorIDs(lstSelectIDs);
            return ditCreatorIDs;
        }

        public void Move(List<int> lstIDs, int dirID)
        {
            doc.Move(lstIDs, dirID);
        }

        /// <summary>
        /// 带权限控制
        /// </summary>
        /// <param name="dirID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public IEnumerable<AttachInfo> GetAttachList(int dirID,int userID)
        {
            IEnumerable<AttachInfo> list = doc.GetAttachList(dirID);

            if (userID != Constants.ADMIN_ID)//管理员不用判断权限
            {
                RecordRightBO right = new RecordRightBO(OTableName.DocRight);
                List<int> lstDocIDs = right.GetBindIDs(userID, RecordRightName.Browse, RightOwnerType.User);//能浏览的文档ID集合
                list = list.Where(Info => Info.CreatorID == userID || lstDocIDs.Contains(Info.BindID));
            }

            return list;
        }

        public List<int> GetIDsByAttachIDs(List<int> attachIDs)
        {
            return doc.GetIDsByAttachIDs(attachIDs);
        }

        public override void Delete(IEnumerable<int> ids)
        {
            foreach (int id in ids)
            {
                this.Delete(id);
            }
        }

        public override void Delete(IEnumerable<string> ids)
        {
            foreach (string id in ids)
            {
                this.Delete(id);
            }
        }

        public override void Delete(int id)
        {
            AttachBO attach = new AttachBO("DocAttach");
            ImageBO picture = new ImageBO("DocPicture");

            this.DeleteTitlePicture(id);

            attach.DeleteByBindID(id);

            picture.DeleteByBindID(id);

            base.Delete(id);

        }

        private void DeleteTitlePicture(object id)
        {
            DocumentInfo info = this.GetInfo(id);
            if (!string.IsNullOrEmpty(info.SmallImage))
            {
                string phyPath = System.Web.HttpContext.Current.Server.MapPath(info.SmallImageAbsPath);
                if (File.Exists(phyPath))
                {
                    File.Delete(phyPath);
                }

                phyPath = System.Web.HttpContext.Current.Server.MapPath(info.BigImageAbsPath);

                if (File.Exists(phyPath))
                {
                    File.Delete(phyPath);
                }
            }
        }

        public IEnumerable<DocumentInfo> GetList(int dirID,int userID, PagerSortSetting pager)
        {

            string condition = null;
            if (pager != null)
            {
                condition = (string)pager.Input;
            }

            IEnumerable<DocumentInfo> list = doc.GetListByDir(dirID, condition).OrderByDescending(T=>T.InputTime);

            if (userID != Constants.ADMIN_ID)//管理员不用判断权限
            {
                RecordRightBO right = new RecordRightBO(OTableName.DocRight);
                List<int> lstDocIDs = right.GetBindIDs(userID, RecordRightName.Browse, RightOwnerType.User);//能浏览的文档ID集合
                list = list.Where(Info => Info.CreatorID == userID || lstDocIDs.Contains(Info.ID));
            }

            if (pager != null)
            {                
                pager.RecordCount = list.Count();
                list = list.Skip(pager.SkipCount).Take(pager.PageSize);
            }            

            return list;
        }

        public override DocumentInfo GetInfo(object id)
        {
            DocumentInfo info = base.GetInfo(id);
            if (id != null)
            {
                SetDelegate(info);
            }
            return info;
        }

        public void SetDelegate(DocumentInfo info)
        {
            ImageBO picture = new ImageBO("DocPicture");
            AttachBO attach = new AttachBO("DocAttach");

            info.GetPictures = docID => picture.GetList(docID, null);
            info.GetAttachs = docID => attach.GetList(docID);
            info.GetDirInfo = dirID => (new DirBO()).GetInfo(dirID);            
        }


        public void SaveImage(ImageInfo pictureInfo, System.Web.HttpPostedFile file, DirInfo dirInfo)
        {
            UserImage userImage = new UserImage(OTableName.DocPicture);


            pictureInfo.OriginImage = userImage.Save(file); //先存原始图片

            pictureInfo.SmallImage = userImage.Save(file, 150);

            pictureInfo.BigImage = userImage.Save(file, 600);

        }
    }
}
